package com.TeaManage.servlet;

import com.TeaManage.bean.TeaCategory;
import com.TeaManage.util.GokJDBCUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "CategoryServlet", urlPatterns = "/CategoryServlet")
public class CategoryServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String action = request.getParameter("action");
        
        if ("add".equals(action)) {
            // 添加分类
            String categoryName = request.getParameter("category_name");
            String description = request.getParameter("description");
            
            // 验证必填字段
            if (categoryName == null || categoryName.trim().isEmpty()) {
                request.setAttribute("error", "分类名称不能为空");
                request.getRequestDispatcher("/views/category/addCategory.jsp").forward(request, response);
                return;
            }
            
            // 检查分类名称是否已存在
            String checkSql = "SELECT COUNT(*) FROM tea_category WHERE category_name = ?";
            int count = GokJDBCUtil.queryForCount(checkSql, categoryName);
            if (count > 0) {
                request.setAttribute("error", "分类名称已存在");
                request.getRequestDispatcher("/views/category/addCategory.jsp").forward(request, response);
                return;
            }
            
            String sql = "INSERT INTO tea_category(category_name, description) VALUES(?, ?)";
            int result = GokJDBCUtil.update(sql, categoryName, description);
            if (result > 0) {
                response.sendRedirect("CategoryServlet");
            }
            
        } else if ("toAdd".equals(action)) {
            // 跳转到新增页面
            request.getRequestDispatcher("/views/category/addCategory.jsp").forward(request, response);
            
        } else if ("deleteById".equals(action)) {
            // 删除分类
            int id = Integer.parseInt(request.getParameter("id"));
            
            // 检查是否有茶叶使用此分类
            String checkSql = "SELECT COUNT(*) FROM tea WHERE tea_category_id = ?";
            int teaCount = GokJDBCUtil.queryForCount(checkSql, id);
            if (teaCount > 0) {
                request.setAttribute("error", "该分类下还有茶叶，无法删除");
                // 重新加载列表页面
                loadCategoryList(request, response);
                return;
            }
            
            String sql = "DELETE FROM tea_category WHERE category_id = ?";
            int result = GokJDBCUtil.update(sql, id);
            response.sendRedirect("CategoryServlet");
            
        } else if ("findById".equals(action)) {
            // 查找分类用于编辑
            int id = Integer.parseInt(request.getParameter("id"));
            String sql = "SELECT * FROM tea_category WHERE category_id = ?";
            TeaCategory category = GokJDBCUtil.queryForObject(sql, TeaCategory.class, id);
            request.setAttribute("category", category);
            request.getRequestDispatcher("/views/category/editCategory.jsp").forward(request, response);
            
        } else if ("update".equals(action)) {
            // 更新分类
            int id = Integer.parseInt(request.getParameter("category_id"));
            String categoryName = request.getParameter("category_name");
            String description = request.getParameter("description");
            
            // 验证必填字段
            if (categoryName == null || categoryName.trim().isEmpty()) {
                request.setAttribute("error", "分类名称不能为空");
                // 重新获取分类信息
                TeaCategory category = GokJDBCUtil.queryForObject("SELECT * FROM tea_category WHERE category_id = ?", TeaCategory.class, id);
                request.setAttribute("category", category);
                request.getRequestDispatcher("/views/category/editCategory.jsp").forward(request, response);
                return;
            }
            
            // 检查分类名称是否已存在（排除当前分类）
            String checkSql = "SELECT COUNT(*) FROM tea_category WHERE category_name = ? AND category_id != ?";
            int count = GokJDBCUtil.queryForCount(checkSql, categoryName, id);
            if (count > 0) {
                request.setAttribute("error", "分类名称已存在");
                TeaCategory category = GokJDBCUtil.queryForObject("SELECT * FROM tea_category WHERE category_id = ?", TeaCategory.class, id);
                request.setAttribute("category", category);
                request.getRequestDispatcher("/views/category/editCategory.jsp").forward(request, response);
                return;
            }
            
            String sql = "UPDATE tea_category SET category_name = ?, description = ? WHERE category_id = ?";
            int result = GokJDBCUtil.update(sql, categoryName, description, id);
            if (result > 0) {
                response.sendRedirect("CategoryServlet");
            }
            
        } else if ("search".equals(action)) {
            // 搜索分类
            String name = request.getParameter("name");
            // 分页参数
            int page = 1;
            int pageSize = 10;
            try {
                page = Integer.parseInt(request.getParameter("page"));
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            } catch (Exception e) {
                page = 1;
                pageSize = 10;
            }
            
            // 构建动态 SQL 和参数列表
            StringBuilder sql = new StringBuilder("SELECT * FROM tea_category WHERE 1=1");
            List<Object> params = new ArrayList<>();
            if (name != null && !name.trim().isEmpty()) {
                sql.append(" AND category_name LIKE ?");
                params.add("%" + name + "%");
            }
            
            // 查询总数
            String countSql = "SELECT COUNT(*) FROM (" + sql.toString() + ") AS total";
            int total = GokJDBCUtil.queryForCount(countSql, params.toArray());
            
            // 添加分页
            sql.append(" ORDER BY category_id DESC LIMIT ?, ?");
            params.add((page - 1) * pageSize);
            params.add(pageSize);
            
            List<TeaCategory> categoryList = GokJDBCUtil.queryAll(sql.toString(), TeaCategory.class, params.toArray());
            
            // 计算总页数
            int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
            
            // 返回结果
            request.setAttribute("categoryList", categoryList);
            request.setAttribute("name", name);
            request.setAttribute("page", page);
            request.setAttribute("pageSize", pageSize);
            request.setAttribute("totalPages", totalPages);
            request.getRequestDispatcher("views/category/category.jsp").forward(request, response);
            
        } else {
            // 默认显示分类列表
            loadCategoryList(request, response);
        }
    }
    
    private void loadCategoryList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 分页参数
        int page = 1;
        int pageSize = 10;
        try {
            page = Integer.parseInt(request.getParameter("page"));
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        } catch (Exception e) {
            page = 1;
            pageSize = 10;
        }
        
        // 查询总数
        String countSql = "SELECT COUNT(*) FROM tea_category";
        int total = GokJDBCUtil.queryForCount(countSql);
        
        // 查询数据
        String sql = "SELECT * FROM tea_category ORDER BY category_id DESC LIMIT ?, ?";
        List<TeaCategory> categoryList = GokJDBCUtil.queryAll(sql, TeaCategory.class, (page-1)*pageSize, pageSize);
        
        int totalPages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        
        request.setAttribute("categoryList", categoryList);
        request.setAttribute("page", page);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("totalPages", totalPages);
        request.getRequestDispatcher("views/category/category.jsp").forward(request, response);
    }
}
